import oss2
from log import logger

class OSSWrapper:

    def __init__(self):
        self.endpoint = 'oss-cn-beijing.aliyuncs.com'
        self.access_key_id = 'LTAI5tNLjDgGSEb91GYnN2TJ'
        self.access_key_secret = 'hom0KBOB9npjRwiMGVdxrsGdfnIbNL'
        self.bucket_name = 'liutf'
        auth = oss2.Auth(self.access_key_id, self.access_key_secret)

        self.bucket = oss2.Bucket(auth, self.endpoint, self.bucket_name)

        # key = "ass.txt"

    def upload_file(self, local_path, object_name):
        try:
            with open(local_path, 'rb') as f:
                self.bucket.put_object(object_name, f)
        except Exception as ex:
            logger.error("文件上传异常:"+str(ex))
            return -1
        logger.info(f"文件 {local_path} 已上传至OSS路径: {object_name}")
        return 0

    def upload_by_form(self,file):
        oss_url = f"https://{self.bucket_name}.{self.endpoint}/{file.filename}"
        try:
            self.bucket.put_object(
                file.filename,
                file.stream,
                headers={
                    'Content-Type': file.content_type
                }
            )
        except Exception as ex:
            logger.error("文件上传异常:" + str(ex))
            return -1
        logger.info(f"文件 {file.filename} 已上传至OSS路径: {oss_url}")
        return oss_url

    def download_file(self, object_name, local_path):
        try:
            self.bucket.get_object_to_file(object_name, local_path)
        except Exception as ex:
            logger.error("文件下载异常:"+str(ex))
            return -1
        logger.info(f"文件 {object_name} 已下载到本地: {local_path}")
        return 0

    def delete_file(self, object_name):
        try:
            self.bucket.delete_object(object_name)
        except Exception as ex:
            logger.error("文件删除异常:"+str(ex))
            return -1
        logger.info(f"文件 {object_name} 已删除")
        return 0


if __name__ == '__main__':
    oss = OSSWrapper()
    oss.upload_file("liu.txt","123")